﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Odbc;
using Gencode.SQLWizz.DataType;
using Gencode.SQLWizz.Controls;





namespace Gencode.SQLWizz.Database
{
	//public delegate void ErrorOccured(string message, string title);
	//public delegate void OutputText(string text);
	//public delegate void QueryFinished();
	public delegate void ReloadView();

	class WZNewDatabase : WZDatabase
	{
		CreateDatabase control;

		public event ReloadView OnReload;

		public WZNewDatabase(LogonData logData, CreateDatabase control)
			: base(logData, "root/new/file", "db.gc")
		{
			this.logData = logData;
			this.control = control;
			
		}

		/// <summary>
		/// starting method of thread
		/// </summary>
		public void CreateNewDatabase()
		{
			Gencode.Common.SQL.DatabaseConection.ODBCConnetionString = "DSN=" + logData.ODBC + ";UID=" + logData.User + ";PWD=" + logData.Password + ";Database=master";
			Gencode.Common.SQL.DatabaseConection.ODBCConnection = new OdbcConnection(Gencode.Common.SQL.DatabaseConection.ODBCConnetionString);
			
			string sqlCreateDBQuery = "CREATE DATABASE "
							   + logData.Database;
							   //+ " ON PRIMARY "
							   //+ " (NAME = " + DBParam.DataFileName + ", "
							   //+ " FILENAME = '" + DBParam.DataPathName + "', "
							   //+ " SIZE = 2MB,"
							   //+ " FILEGROWTH =" + DBParam.DataFileGrowth + ") "
							   //+ " LOG ON (NAME =" + DBParam.LogFileName + ", "
							   //+ " FILENAME = '" + DBParam.LogPathName + "', "
							   //+ " SIZE = 1MB, "
							   //+ " FILEGROWTH =" + DBParam.LogFileGrowth + ") ";
			errorSucces = Gencode.Common.SQL.SimpleQuerry.Execute(sqlCreateDBQuery, true);

			if (ErrorSucces)
			{
				Gencode.Common.SQL.DatabaseConection.ODBCConnetionString = "DSN=" + logData.ODBC + ";UID=" + logData.User + ";PWD=" + logData.Password + ";Database=" + logData.Database;
				Gencode.Common.SQL.DatabaseConection.ODBCConnection = new OdbcConnection(Gencode.Common.SQL.DatabaseConection.ODBCConnetionString);

				errorSucces = Gencode.Common.SQL.SimpleQuerry.Execute("exec('ALTER DATABASE " + logData.Database + " SET RECOVERY SIMPLE')", true);
				errorSucces = Gencode.Common.SQL.SimpleQuerry.Execute("exec('ALTER DATABASE " + logData.Database + " set auto_close off')", true);

				bool tmp = true;
				int index = 0;
				while (tmp)
				{
					tmp = ExecuteSqlFiles(index);
					index++;

					if (!ErrorSucces)
					{
						tmp = false;
					}
				}

				ExecuteFinishEvent();
			}
			else
			{
				ExecuteErrorEvent("Eine Datenbank mit diesem Namen existiert bereits.\nBitte wählen Sie einen anderen Datenbanknamen aus.", "Fehler");
				if (OnReload != null)
					OnReload();
			}
		}
		/*
		public bool ExecuteSqlFiles(int index)
		{
			if (index < sqlFilenames.Count && File.Exists("SQL\\" + sqlFilenames[index]))
			{
				FileInfo file = new FileInfo("SQL\\" + sqlFilenames[index]);

				string script = file.OpenText().ReadToEnd();
				string[] scripts = PrepareScripts(script);

				for (int i = 0; i < scripts.Length; i++)
				{
					if (scripts[i] != string.Empty)
					{
						if (CheckForPrints(scripts[i]))
						{
							if(OnOutput != null)
								OnOutput(scripts[i]);
						}
						else
						{
							ErrorSucces = Gencode.Common.SQL.SimpleQuerry.Execute(scripts[i]);

							if (!ErrorSucces)
							{
								if (OnError != null)
								{
									OnError("Es ist ein Fehler aufgetreten.\nFür genauere Informationen schauen sie bitte im Logfile nach.", "Fehler");
								}
								return false;
							}
						}
					}
				}

				return true;
			}

			return false;
		}
		*/
		/*
		private string[] PrepareScripts(string script)
		{
			var statements = script.Replace("go", ";");
			statements = statements.Replace("GO", ";");
			return statements.Split(';');
		}

		private bool CheckForPrints(string script)
		{
			string tmp = script.TrimStart();
			if (tmp.StartsWith("print", true, null))
				return true;

			return false;
		}

		private void ReadFilelist()
		{
			sqlFilenames = new List<string>();

			XmlDocument doc = new XmlDocument();
			doc.Load("SQL\\sqlfiles.xml");
			XmlNodeList nodes = doc.SelectNodes("root/new/file");
			foreach (XmlNode node in nodes)
			{
				sqlFilenames.Add(node.Attributes["name"].Value.ToString());
			}

		}*/
	}
}
